#include "piece_genera.hpp"
#include "math.h"

bool Piece_Genera::move(const Coordinate &goal) {
    Coordinate spacing = goal - coor;
    if (spacing * spacing == 1) {
        //遍历红黑两个九宫中心
        for (int i = 8; i >= 0; i -= 7) {
            Coordinate centSpacing = Coordinate(i, 4) - goal;
            Piece &goalPiece = *pieces[gameMap[goal]];
            if (centSpacing * centSpacing <= 2) {
                if (goalPiece.isLife()) {
                    if (goalPiece.getColor() != color)
                        goalPiece.setLife(false);
                    else
                        return false;
                }
                updateCoor(gameMap, goal);
                return true;
            }
        }
    }
        //如果间隔大于五判断是否将照面从而吃掉对面的将军
    else if (spacing.x >= 5 && spacing.y == 0) {
        Piece &goalPiece = *pieces[gameMap[goal]];
        if (gameMap[goal] == BLACK_GENERA || gameMap[goal] == RED_GENERA) {
            Coordinate add = spacing / abs(spacing.x);
            int num = 0;
            for (Coordinate it = coor; it != goal; it += add) {
                num += pieces[gameMap[goal]]->isLife();
            }
            if (num == 0) {
                goalPiece.setLife(false);
                updateCoor(gameMap, goal);
                return true;
            }
        }
    }
    return false;
}

void Piece_Genera::init() {
    switch (pt) {
        case PieceType::RED_GENERA:
            coor.x = 9;
            coor.y = 4;
            color = RED;
            break;
        case PieceType::BLACK_GENERA:
            coor.x = 0;
            coor.y = 4;
            color = BLACK;
            break;
        default:
            break;
    }
    life = true;
}

Piece_Genera::~Piece_Genera() {}
